const { pool } = require("../config/database");
const logger = require('../utils/logger');

class LoginLogService {
  /**
   * 创建登录日志
   * @param {Object} logData 日志数据
   * @param {number} logData.userId 用户ID
   * @param {string} logData.username 用户名
   * @param {string} logData.ip IP地址
   * @param {string} logData.userAgent 用户代理
   * @param {boolean} logData.success 是否登录成功
   * @param {string} [logData.failReason] 失败原因
   */
  static async create(logData) {
    try {
      const sql = `
        INSERT INTO login_logs 
        (user_id, username, ip, user_agent, status, message, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, NOW())
      `;
      
      const params = [
        logData.userId,
        logData.username,
        logData.ip,
        logData.userAgent,
        logData.success ? 1 : 0,  // 转换 success 为 status
        logData.failReason || null  // 使用 failReason 作为 message
      ];

      await pool.query(sql, params);
    } catch (error) {
      logger.error('创建登录日志失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户最近的登录记录
   * @param {number} userId 用户ID
   * @param {number} limit 限制数量
   */
  static async getRecentLogs(userId, limit = 5) {
    try {
      const sql = `
        SELECT 
          id,
          user_id,
          username,
          ip,
          user_agent,
          status as success,
          message as fail_reason,
          created_at
        FROM login_logs 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT ?
      `;
      
      const [logs] = await pool.query(sql, [userId, limit]);
      return logs.map(log => ({
        ...log,
        success: log.success === 1  // 转换 status 为 boolean
      }));
    } catch (error) {
      logger.error('获取登录日志失败:', error);
      throw error;
    }
  }
}

module.exports = LoginLogService; 